import { createRouter, createWebHistory } from 'vue-router'
import { routes } from '@/router/routes'
import { useUserStore } from '@/stores/modules/user'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
  scrollBehavior() {
    return {
      top: 0,
      left: 0
    }
  }
})
router.beforeEach((to, from) => {
  const userStore = useUserStore()
  // 路由守卫拦截未登录的账户进入主页
  // 定义一个变量接收会话存储的数据来识别是否登录成功
  const isAuthenticated = JSON.parse(sessionStorage.getItem('user') as string) || {}
  const { user } = isAuthenticated
  if (user == undefined && to.name !== 'login') return { name: 'login' }
})

router.afterEach((to, from) => {
  if (to.meta && to.meta.title) document.title = to.meta.title as string
})

export default router
